﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using ENT = CPPEI.Coolzon.DesignServer.Domain.Entities;
using SER = CPPEI.Coolzon.DesignServer.Domain.Services;
using MOD = CPPEI.Coolzon.DesignServer.Domain.Models;
using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.DesignServer.Data;

using DT = CPPEI.Coolzon.Designtime.Metadata;

namespace CPPEI.Coolzon.DesignServer.ServiceImplement
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class DesignService : IDesignService
    {
        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <param name="userAccount"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Data.SingleResult<Data.User> Login(Data.LoginRequest request)
        {
            Data.User user = new Data.User();
            user.UserAccount = request.UserAccount;
            user.Token = request.UserAccount;
            user.UserIdentity = request.UserAccount;
            user.UserName = request.UserAccount;
            return new Data.SingleResult<Data.User>(true, 0, string.Empty, user);
        }

        /// <summary>
        /// 创建工作空间
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Data.SingleResult<Data.Workspace> CreateWorkspace(Data.CreateWorkspaceRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);

            SER.WorkspaceService service = new SER.WorkspaceService();
            SER.ListResult<ENT.Workspace> list = service.Find(request.Token, request.Computer);
            if (list.Data != null)
            {
                if (list.Data.Any(p => p.LocalPath == request.LocalPath))
                {
                    return new Data.SingleResult<Data.Workspace>(false, 1, "工作空间已存在！", null);
                }
            }
            SER.SingleResult<ENT.Workspace> result = service.Create(request.LocalPath, userIdentity, request.Computer);
            if (result.IsSuccess)
            {
                Data.Workspace item = new Data.Workspace();
                item.Id = result.Data.Id;
                item.LocalPath = result.Data.LocalPath;
                item.Computer = result.Data.Computer;
                item.CreatedTime = result.Data.CreatedTime;
                item.Creator = result.Data.Creator;
                return new Data.SingleResult<Data.Workspace>(true, 0, string.Empty, item);
            }

            return new Data.SingleResult<Data.Workspace>(false, 1, string.Empty, null);
        }

        /// <summary>
        /// 获取用户可用的工作空间
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Data.ListResult<Data.Workspace> GetWorkspaceList(Data.GetWorkspaceListRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);

            SER.WorkspaceService service = new Domain.Services.WorkspaceService();
            SER.ListResult<ENT.Workspace> result = service.Find(userIdentity, request.Computer);

            if (result.IsSuccess)
            {
                List<Data.Workspace> list = new List<Data.Workspace>();
                for (int index = 0; index < result.Data.Count; index++)
                {
                    Data.Workspace item = new Data.Workspace();
                    item.Id = result.Data[index].Id;
                    item.LocalPath = result.Data[index].LocalPath;
                    item.Computer = result.Data[index].Computer;
                    item.CreatedTime = result.Data[index].CreatedTime;
                    item.Creator = result.Data[index].Creator;

                    list.Add(item);
                }

                return new Data.ListResult<Data.Workspace>(true, 0, string.Empty, list);
            }

            return new Data.ListResult<Data.Workspace>(false, 1, string.Empty, null);
        }

        /// <summary>
        /// 创建方案
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Data.SingleResult<Data.Solution> CreateSolution(Data.CreateSolutionRequest request)
        {

            string userIdentity = TokenUtil.GetUserIdentity(request.Token);

            SER.SolutionService service = new Domain.Services.SolutionService();
            SER.SingleResult<ENT.Solution> result = service.Create(request.Name, request.Caption, request.Type, request.RTVersion, userIdentity);

            if (result.IsSuccess)
            {
                Data.Solution item = new Data.Solution();
                item.Id = result.Data.Id;
                item.Name = result.Data.Name;
                item.Caption = result.Data.Caption;
                item.Type = result.Data.Type;
                item.Version = result.Data.Version;
                item.RTVersion = result.Data.RTVersion;
                item.CreatedTime = result.Data.CreatedTime;
                item.Creator = result.Data.Creator;

                return new Data.SingleResult<Data.Solution>(true, 0, string.Empty, item);
            }

            return new Data.SingleResult<Data.Solution>(false, 1, result.Message, null);
        }

        /// <summary>
        /// 获取工作空间列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Data.ListResult<Data.Solution> GetSolutionList(Data.GetSolutionListRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.SolutionService service = new Domain.Services.SolutionService();
            SER.ListResult<ENT.Solution> result = service.Find(userIdentity);

            if (result.IsSuccess)
            {
                List<Data.Solution> list = new List<Data.Solution>();
                for (int index = 0; index < result.Data.Count; index++)
                {
                    string dir = DT.Storage.GetSolutionDirectory(result.Data[index].Id);
                    if (!Directory.Exists(dir))
                    {
                        if (userIdentity != result.Data[index].Creator)
                        {
                            continue;
                        }
                    }
                    Data.Solution item = new Data.Solution();
                    item.Id = result.Data[index].Id;
                    item.Name = result.Data[index].Name;
                    item.Caption = result.Data[index].Caption;
                    item.Type = result.Data[index].Type;
                    item.Version = result.Data[index].Version;
                    item.RTVersion = result.Data[index].RTVersion;
                    item.CreatedTime = result.Data[index].CreatedTime;
                    item.Creator = result.Data[index].Creator;
                    item.IsExistSolution = Directory.Exists(dir);

                    SER.ItemService itemService = new Domain.Services.ItemService();
                    SER.SingleResult<ENT.Item> itemResult = itemService.GetItem(item.Id, item.Id);
                    if (itemResult.Data != null)
                    {
                        item.UpdateTime = itemResult.Data.Updatedtime;
                    }
                    list.Add(item);
                }

                return new Data.ListResult<Data.Solution>(true, 0, string.Empty, list);
            }

            return new Data.ListResult<Data.Solution>(false, 1, string.Empty, null);
        }

        /// <summary>
        /// 获取方案中的项目概要信息列表，用于在获取最新方案的时候提供给客户端比较
        /// </summary>
        /// <param name="token"></param>
        /// <param name="solutionId"></param>
        /// <returns></returns>
        public Data.ListResult<Data.ItemSummary> GetSolutionItemSummaries(Data.GetItemSummaryListRequest request)
        {
            SER.ItemService service = new Domain.Services.ItemService();
            SER.ListResult<ENT.Item> result = service.GetItems(request.SolutionId);
            if (result.IsSuccess)
            {
                List<Data.ItemSummary> list = new List<Data.ItemSummary>();
                for (int index = 0; index < result.Data.Count; index++)
                {
                    Data.ItemSummary item = new Data.ItemSummary();
                    item.Id = result.Data[index].Id;
                    item.Name = result.Data[index].Name;
                    item.IsEditing = result.Data[index].IsEditing;
                    item.Version = result.Data[index].Version;
                    item.Editor = result.Data[index].Editor;
                    list.Add(item);
                }
                return new Data.ListResult<Data.ItemSummary>(true, 0, string.Empty, list);
            }
            return new Data.ListResult<Data.ItemSummary>(false, 1, string.Empty, null);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="token"></param>
        /// <param name="solutionId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public Data.GetLatestVersionResponse GetLatestVersion(Data.GetLatestVersionRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.ItemService service = new Domain.Services.ItemService();

            SER.SingleResult<ENT.Item> result = service.GetItem(request.SolutionId, request.Id);
            if (result.IsSuccess)
            {
                if (result.Data == null)
                {
                    return new Data.GetLatestVersionResponse(true, 0, string.Empty,
                           Guid.Empty,
                           string.Empty,
                           0,
                           Guid.Empty,
                           Guid.Empty,
                           0,
                           new MemoryStream(), true, request.Token,
                           string.Empty);
                }
                if (!string.IsNullOrEmpty(result.Data.Path))
                {
                    string absoluteFilePath = DT.Storage.GetItemFilePath(request.SolutionId, result.Data.Path);
                    Logger.DebugToTag(Library.LogTAG, string.Format("获取最新版本，项:{0},路径:{1}", result.Data.Name, absoluteFilePath));

                    return new Data.GetLatestVersionResponse(true, 0, string.Empty,
                        result.Data.Id,
                        result.Data.Name,
                        result.Data.Version,
                        result.Data.ParentId,
                        result.Data.FolderId,
                        result.Data.Type,
                        new FileStream(absoluteFilePath, FileMode.Open, FileAccess.Read), result.Data.IsEditing, result.Data.Editor,
                        result.Data.Extension);
                }
                Logger.DebugToTag(Library.LogTAG, string.Format("获取最新版本，项:{0},没有文件", result.Data.Name));
                return new Data.GetLatestVersionResponse(true, 0, string.Empty,
                    result.Data.Id,
                    result.Data.Name,
                    result.Data.Version,
                    result.Data.ParentId,
                    result.Data.FolderId,
                    result.Data.Type,
                    new MemoryStream(), result.Data.IsEditing, result.Data.Editor,
                    result.Data.Extension);
            }
            Logger.DebugToTag(Library.LogTAG, string.Format("{0}获取最新版本，方案:{1},项:{2},失败", userIdentity, request.SolutionId, request.Id));
            return new Data.GetLatestVersionResponse(false, 1, string.Empty,
                Guid.Empty,
                string.Empty,
                0,
                Guid.Empty,
                Guid.Empty,
                0,
                new MemoryStream(), result.Data.IsEditing, result.Data.Editor,
                string.Empty);
        }

        public Data.CheckInResponse CheckIn(Data.CheckInRequest message)
        {
            string userIdentity = TokenUtil.GetUserIdentity(message.Token);
            SER.ItemService service = new Domain.Services.ItemService();
            ENT.Item item = new ENT.Item();
            item.Id = message.Id;
            item.Name = message.Name;
            item.Version = message.Version;
            item.FolderId = message.FolderId;
            item.SolutionId = message.SolutionId;
            item.Type = message.Type;
            item.ParentId = message.ParentId;
            item.Updatedtime = DateTime.Now;
            item.Extension = message.Extension;

            SER.SingleResult<ENT.Item> result = service.CheckIn(userIdentity, item, message.Content);

            if (result.IsSuccess)
            {
                return new Data.CheckInResponse(true, 0, message.Id, message.Name, result.Data.Version);
            }
            return new Data.CheckInResponse(false, 1, message.Id, message.Name, message.Version);
        }

        /// <summary>
        /// 签出项目
        /// </summary>
        /// <param name="token"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public Data.ServiceResult CheckOut(Data.CheckOutRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.ItemService service = new Domain.Services.ItemService();

            SER.ServiceResult result = service.CheckOut(userIdentity, request.SolutionId, request.Id,request.WorkSpaceId);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, result.Message);
        }

        /// <summary>
        /// 撤销项目
        /// </summary>
        /// <param name="token"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public Data.UndoResponse Undo(Data.UndoRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.ItemService service = new Domain.Services.ItemService();

            SER.SingleResult<ENT.Item> result = service.Undo(userIdentity, request.SolutionId, request.Id);

            if (result.IsSuccess)
            {
                if (!string.IsNullOrEmpty(result.Data.Path))
                {
                    string absoluteFilePath = DT.Storage.GetItemFilePath(request.SolutionId, result.Data.Path);
                    return new Data.UndoResponse(true, 0, string.Empty,
                        result.Data.Id,
                        result.Data.Name,
                        result.Data.Version,
                        result.Data.ParentId,
                        result.Data.FolderId,
                        result.Data.Type,
                        new FileStream(absoluteFilePath, FileMode.Open, FileAccess.Read),
                        result.Data.Extension);
                }
                return new Data.UndoResponse(true, 0, string.Empty,
                    result.Data.Id,
                    result.Data.Name,
                    result.Data.Version,
                    result.Data.ParentId,
                    result.Data.FolderId,
                    result.Data.Type,
                    new MemoryStream(),
                    result.Data.Extension);
            }
            return new Data.UndoResponse(false, 1, string.Empty,
                Guid.Empty,
                string.Empty,
                0,
                Guid.Empty,
                Guid.Empty,
                0,
                new MemoryStream(),
                string.Empty);
        }

        /// <summary>
        /// 获取要删除记录列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Data.ListResult<Data.DeletingList> GetDeletingList(Data.DeleteRequest request)
        {

            SER.ItemService service = new Domain.Services.ItemService();
            SER.ListResult<ENT.Item> result = service.GetDeletingList(request.SolutionId, request.Id);

            if (result.IsSuccess)
            {
                List<Data.DeletingList> list = new List<Data.DeletingList>();

                for (int index = 0; index < result.Data.Count; index++)
                {
                 
                    Data.DeletingList item = new Data.DeletingList();
             
                    item.ItemId = result.Data[index].Id;
                    item.ItemName = result.Data[index].Name;
                    item.ItemVersion = result.Data[index].Version;
                    item.ItemParentId = result.Data[index].ParentId;
                    item.ItemFolderId = result.Data[index].FolderId;
                    item.ItemType = result.Data[index].Type;
                    //item.Content = Content;
                    item.ItemExtension = result.Data[index].Extension;
                    item.ItemPath = result.Data[index].Path;

                    list.Add(item);
                }

                return new Data.ListResult<Data.DeletingList>(true, 0, string.Empty, list);
                //return list;
            }

           return new Data.ListResult<Data.DeletingList>(false, 1, string.Empty, null);
            // return list;
        }

        /// <summary>
        /// 服务器标记为删除
        /// </summary>
        /// <param name="token"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public Data.ServiceResult Delete(Data.DeleteRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.ItemService service = new Domain.Services.ItemService();

            SER.ServiceResult result = service.Delete(userIdentity, request.SolutionId, request.Id,request.WorkSpaceId);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, result.Message);
        }

        #region datasource

        public Data.ServiceResult CreateDataSource(Data.CreateDataSourceRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);

            SER.DataSourceService service = new SER.DataSourceService();
            SER.SingleResult<ENT.DataSource> result = service.CreateDataSource(request.DataSource.Id,
                request.DataSource.SolutionId,
                request.DataSource.Name,
                request.DataSource.Caption,
                request.DataSource.Type,
                request.DataSource.Version.ToString(),
                request.DataSource.RTVersion.ToString(),
                request.DataSource.Address,
                request.DataSource.AuthenticationMode,
                request.DataSource.AuthenticationUser,
                request.DataSource.AuthenticationPassword,
                userIdentity);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, string.Empty);
        }

        public Data.ServiceResult CreateDataSet(Data.CreateDataSetRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);

            #region 检查参数名称
            for (int index = 0; index < request.DataSet.Parameters.Length; index++)
            {
                for (int indexR2 = 0; indexR2 < request.DataSet.Parameters.Length; indexR2++)
                {
                    if (index != indexR2 &&
                        string.Equals(request.DataSet.Parameters[index].Name, request.DataSet.Parameters[indexR2].Name))
                    {
                        return new Data.ServiceResult(false, 1, string.Format("参数{0}重复", request.DataSet.Parameters[index].Name));
                    }
                }
            }
            #endregion

            MOD.DataSet dataSet = new MOD.DataSet();
            dataSet.Id = request.DataSet.Id;
            dataSet.Name = request.DataSet.Name;
            dataSet.Caption = request.DataSet.Caption;
            dataSet.Type = request.DataSet.Type;
            dataSet.ValueString = request.DataSet.ValueString;
            dataSet.DataSourceId = request.DataSourceId;
            dataSet.Parameters = new List<ENT.DataParameter>();
            dataSet.Creator = userIdentity;
            dataSet.CreatedTime = DateTime.Now;

            for (int index = 0; index < request.DataSet.Parameters.Length; index++)
            {
                ENT.DataParameter parameter = new ENT.DataParameter();
                parameter.Id = request.DataSet.Parameters[index].Id;
                parameter.Name = request.DataSet.Parameters[index].Name;
                parameter.Caption = request.DataSet.Parameters[index].Caption;
                parameter.DataSetId = dataSet.Id;
                parameter.ValueType = request.DataSet.Parameters[index].ValueType;
                parameter.DataSourceId = dataSet.DataSourceId;
                parameter.Type = request.DataSet.Parameters[index].Type;
                dataSet.Parameters.Add(parameter);
            }

            SER.DataSourceService service = new SER.DataSourceService();
            SER.ServiceResult result = service.CreateDataSet(dataSet);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, string.Empty);
        }

        public Data.ServiceResult UpdateDataSource(Data.CreateDataSourceRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);

            SER.DataSourceService service = new SER.DataSourceService();
            SER.ServiceResult result = service.UpdateDataSource(request.DataSource.Id,
                request.DataSource.SolutionId,
                request.DataSource.Name,
                request.DataSource.Caption,
                request.DataSource.Type,
                request.DataSource.Version.ToString(),
                request.DataSource.RTVersion.ToString(),
                request.DataSource.Address,
                request.DataSource.AuthenticationMode,
                request.DataSource.AuthenticationUser,
                request.DataSource.AuthenticationPassword,
                userIdentity);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, string.Empty);
        }

        public Data.ServiceResult UpdateDataSet(Data.CreateDataSetRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);

            #region 检查参数名称
            for (int index = 0; index < request.DataSet.Parameters.Length; index++)
            {
                for (int indexR2 = 0; indexR2 < request.DataSet.Parameters.Length; indexR2++)
                {
                    if (index != indexR2 &&
                        string.Equals(request.DataSet.Parameters[index].Name, request.DataSet.Parameters[indexR2].Name))
                    {
                        return new Data.ServiceResult(false, 1, string.Format("参数{0}重复", request.DataSet.Parameters[index].Name));
                    }
                }
            }
            #endregion

            MOD.DataSet dataSet = new MOD.DataSet();
            dataSet.Id = request.DataSet.Id;
            dataSet.Name = request.DataSet.Name;
            dataSet.Caption = request.DataSet.Caption;
            dataSet.Type = request.DataSet.Type;
            dataSet.ValueString = request.DataSet.ValueString;
            dataSet.DataSourceId = request.DataSourceId;
            dataSet.Parameters = new List<ENT.DataParameter>();
            dataSet.Creator = userIdentity;
            dataSet.CreatedTime = DateTime.Now;

            for (int index = 0; index < request.DataSet.Parameters.Length; index++)
            {
                ENT.DataParameter parameter = new ENT.DataParameter();
                parameter.Id = request.DataSet.Parameters[index].Id;
                parameter.Name = request.DataSet.Parameters[index].Name;
                parameter.Caption = request.DataSet.Parameters[index].Caption;
                parameter.DataSetId = dataSet.Id;
                parameter.ValueType = request.DataSet.Parameters[index].ValueType;
                parameter.Type = request.DataSet.Parameters[index].Type;
                parameter.DataSourceId = dataSet.DataSourceId;
                dataSet.Parameters.Add(parameter);
            }

            SER.DataSourceService service = new SER.DataSourceService();
            SER.ServiceResult result = service.UpdateDataSet(dataSet);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, string.Empty);
        }

        public Data.ListResult<Data.DataSource> GetDataSourceList(Data.GetDataSourceListRequest request)
        {
            List<Data.DataSource> list = new List<Data.DataSource>();

            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.DataSourceService service = new SER.DataSourceService();
            SER.ListResult<ENT.DataSource> result = service.FindDataSourceList(userIdentity, Guid.Empty);
            for (int index = 0; index < result.Data.Count; index++)
            {
                Data.DataSource dataSource = new Data.DataSource();
                dataSource.Id = result.Data[index].Id;
                dataSource.SolutionId = result.Data[index].SolutionId;
                dataSource.Name = result.Data[index].Name;
                dataSource.Caption = result.Data[index].Caption;
                dataSource.Version = new Version(result.Data[index].Version);
                dataSource.RTVersion = new Version(result.Data[index].RTVersion);
                dataSource.Type = result.Data[index].Type;
                dataSource.Address = result.Data[index].Address;
                dataSource.AuthenticationMode = result.Data[index].AuthenticationMode;
                dataSource.AuthenticationUser = result.Data[index].AuthenticationUser;
                dataSource.AuthenticationPassword = result.Data[index].AuthenticationPassword;
                dataSource.Creator = result.Data[index].Creator;
                dataSource.CreatedTime = result.Data[index].CreatedTime;
                if (result.Data[index].PublishedTime != null)
                {
                    dataSource.PublishedTime = result.Data[index].PublishedTime.Value;
                }

                if (!string.IsNullOrEmpty(result.Data[index].PublishedVersion))
                {
                    dataSource.PublishedVersion = new Version(result.Data[index].PublishedVersion);
                }
                else
                {
                    dataSource.PublishedVersion = new Version(0, 0);
                }

                list.Add(dataSource);
            }
            return new Data.ListResult<Data.DataSource>(true, 0, string.Empty, list);
        }

        public Data.ListResult<Data.DataSet> GetDataSetList(Data.GetDataSetListRequest request)
        {
            List<Data.DataSet> list = new List<Data.DataSet>();
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.DataSourceService service = new SER.DataSourceService();
            SER.ListResult<MOD.DataSet> result = service.FindDataSetList(userIdentity, request.DataSourceId);

            for (int index = 0; index < result.Data.Count; index++)
            {
                Data.DataSet dataSet = new Data.DataSet();
                dataSet.Id = result.Data[index].Id;
                dataSet.Name = result.Data[index].Name;
                dataSet.Caption = result.Data[index].Caption;
                dataSet.Type = result.Data[index].Type;
                dataSet.ValueString = result.Data[index].ValueString;
                List<Data.DataParameter> parameterList = new List<Data.DataParameter>();

                for (int indexParameter = 0; indexParameter < result.Data[index].Parameters.Count; indexParameter++)
                {
                    Data.DataParameter dataParameter = new Data.DataParameter();
                    dataParameter.Id = result.Data[index].Parameters[indexParameter].Id;
                    dataParameter.Caption = result.Data[index].Parameters[indexParameter].Caption;
                    dataParameter.Name = result.Data[index].Parameters[indexParameter].Name;
                    dataParameter.ValueType = result.Data[index].Parameters[indexParameter].ValueType;
                    dataParameter.Type = result.Data[index].Parameters[indexParameter].Type;
                    parameterList.Add(dataParameter);
                }
                dataSet.Parameters = parameterList.ToArray();

                list.Add(dataSet);
            }
            return new Data.ListResult<Data.DataSet>(true, 0, string.Empty, list);
        }

        public Data.ServiceResult DeleteDataSource(Data.DeleteDataSourceRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.DataSourceService service = new SER.DataSourceService();
            SER.ServiceResult result = service.DeleteDataSource(request.DataSourceId);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, string.Empty);
        }

        public Data.ServiceResult DeleteDataSet(Data.DeleteDataSetRequest request)
        {
            SER.DataSourceService service = new SER.DataSourceService();
            SER.ServiceResult result = service.DeleteDataSet(request.DataSourceId, request.DataSetId);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, string.Empty);
        }

        /// <summary>
        /// 发布数据源
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ServiceResult PublishDataSource(PublishDataSourceRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.DataSourceService service = new SER.DataSourceService();

            SER.SingleResult<MOD.PublishedDataSource> pubResult = service.PubDataSource(request.DataSourceId);
            if (pubResult.IsSuccess)
            {
                Logger.DebugToTag(Library.LogTAG, string.Format("开始发布数据源{0}文件!", pubResult.Data.DataSource.Name));
                Metadata.DataSource dataSource = CPPEI.Coolzon.DesignServer.DataSourceConverter.Convert(pubResult.Data);
                if (Coolzon.Runtime.Metadata.Storage.SaveDataSource(dataSource))
                {
                    Logger.DebugToTag(Library.LogTAG, string.Format("发布数据源{0}文件，成功!", pubResult.Data.DataSource.Name));
                    // 发布文件
                    return new ServiceResult(true, 0, string.Empty);
                }
                Logger.DebugToTag(Library.LogTAG, string.Format("发布数据源{0}文件，失败!", pubResult.Data.DataSource.Name));
                return new ServiceResult(false, 1, string.Empty);
            }
            return new ServiceResult(false, 1, string.Empty);
        }

        public ListResult<PublishedDataSource> GetPublishedDataSources(GetPublishedDataSourceListRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.DataSourceService service = new SER.DataSourceService();
            SER.ListResult<MOD.PublishedDataSource> modelDataSourceList = service.GetPublishedDataSourceList(request.SolutionId);

            if (modelDataSourceList.IsSuccess)
            {
                List<PublishedDataSource> dataSourceList = new List<PublishedDataSource>();
                for (int indexDSource = 0; indexDSource < modelDataSourceList.Data.Count; indexDSource++)
                {
                    PublishedDataSource dcPDataSouce = new PublishedDataSource();
                    dcPDataSouce.Id = modelDataSourceList.Data[indexDSource].DataSource.DataSourceId;
                    dcPDataSouce.Name = modelDataSourceList.Data[indexDSource].DataSource.Name;
                    dcPDataSouce.Address = modelDataSourceList.Data[indexDSource].DataSource.Address;
                    dcPDataSouce.AuthenticationMode = modelDataSourceList.Data[indexDSource].DataSource.AuthenticationMode;
                    dcPDataSouce.AuthenticationPassword = modelDataSourceList.Data[indexDSource].DataSource.AuthenticationPassword;
                    dcPDataSouce.AuthenticationUser = modelDataSourceList.Data[indexDSource].DataSource.AuthenticationUser;
                    dcPDataSouce.Caption = modelDataSourceList.Data[indexDSource].DataSource.Caption;
                    dcPDataSouce.CreatedTime = modelDataSourceList.Data[indexDSource].DataSource.CreatedTime;
                    dcPDataSouce.Creator = modelDataSourceList.Data[indexDSource].DataSource.Creator;
                    dcPDataSouce.PublishedTime = modelDataSourceList.Data[indexDSource].DataSource.PublishedTime.Value;
                    dcPDataSouce.PublishedVersion = new Version(modelDataSourceList.Data[indexDSource].DataSource.PublishedVersion);
                    dcPDataSouce.RTVersion = new Version(modelDataSourceList.Data[indexDSource].DataSource.RTVersion);
                    dcPDataSouce.SolutionId = modelDataSourceList.Data[indexDSource].DataSource.SolutionId;
                    dcPDataSouce.SolutionId = modelDataSourceList.Data[indexDSource].DataSource.SolutionId;
                    dcPDataSouce.Type = modelDataSourceList.Data[indexDSource].DataSource.Type;

                    List<PublishedDataSet> dcDataSetList = new List<PublishedDataSet>();

                    for (int indexDSet = 0; indexDSet < modelDataSourceList.Data[indexDSource].DataSets.Count; indexDSet++)
                    {
                        var modelDataSet = modelDataSourceList.Data[indexDSource].DataSets[indexDSet];
                        PublishedDataSet dcDataSet = new PublishedDataSet();
                        dcDataSet.Id = modelDataSet.DataSet.DataSetId;
                        dcDataSet.Caption = modelDataSet.DataSet.Caption;
                        dcDataSet.Name = modelDataSet.DataSet.Name;
                        dcDataSet.Type = modelDataSet.DataSet.Type;
                        dcDataSet.ValueString = modelDataSet.DataSet.ValueString;

                        dcDataSetList.Add(dcDataSet);

                        // convert parameter
                        List<PublishedDataParameter> dcDataParameterList = new List<PublishedDataParameter>();
                        for (int indexDParam = 0; indexDParam < modelDataSet.DataParameters.Count; indexDParam++)
                        {
                            var modelDataParam = modelDataSet.DataParameters[indexDParam];
                            PublishedDataParameter dcDataParam = new PublishedDataParameter();
                            dcDataParam.Id = modelDataParam.DataParameterId;
                            dcDataParam.Caption = modelDataParam.Caption;
                            dcDataParam.Name = modelDataParam.Name;
                            dcDataParam.ValueType = modelDataParam.ValueType;
                            dcDataParam.Type = modelDataParam.Type;

                            dcDataParameterList.Add(dcDataParam);
                        }
                        dcDataSet.Parameters = dcDataParameterList.ToArray();
                    }
                    dcPDataSouce.DataSet = dcDataSetList.ToArray();

                    dataSourceList.Add(dcPDataSouce);
                }
                return new ListResult<PublishedDataSource>(true, 0, string.Empty, dataSourceList);
            }
            return new ListResult<PublishedDataSource>(false, 1, string.Empty, null);
        }
        #endregion

        /// <summary>
        /// 获取操作历史
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ListResult<ItemHistory> GetItemHistoryList(GetItemHistoryListRequest request)
        {
            SER.ItemService service = new Domain.Services.ItemService();
            SER.ListResult<ENT.ItemHistory> result = service.GetHistories(request.ItemId);

            if (result.IsSuccess)
            {
                List<Data.ItemHistory> list = new List<Data.ItemHistory>();
                for (int index = 0; index < result.Data.Count; index++)
                {
                    Data.ItemHistory item = new Data.ItemHistory();
                    item.Id = result.Data[index].Id;
                    item.ItemId = result.Data[index].ItemId;
                    item.OperatedTime = result.Data[index].OperatedTime;
                    item.Operator = result.Data[index].Operator;
                    item.Version = result.Data[index].ItemVersion;
                    if (result.Data[index].Action == 0x00)
                    {
                        item.Action = "签入";
                    }
                    list.Add(item);
                }

                return new Data.ListResult<Data.ItemHistory>(true, 0, string.Empty, list);
            }

            return new Data.ListResult<Data.ItemHistory>(false, 1, string.Empty, null);
        }

        /// <summary>
        /// 获取特定版本
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GetItemSpecificVersionResponse GetItemSpecificVersion(Data.GetItemSpecificVersionRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.ItemService service = new Domain.Services.ItemService();

            SER.SingleResult<ENT.ItemHistory> result = service.GetItemHistory(request.SolutionId, request.ItemId, request.Version, userIdentity);
            if (result.IsSuccess)
            {
                if (!string.IsNullOrEmpty(result.Data.ItemPath))
                {
                    string absoluteFilePath = DT.Storage.GetItemFilePath(request.SolutionId, result.Data.ItemPath);
                    Logger.DebugToTag(Library.LogTAG, string.Format("获取特定版本，项:{0},路径:{1}", result.Data.ItemName, absoluteFilePath));

                    //20150810如果当前用户和签出者是同一个人，则将item更新为签入状态
                    SER.SingleResult<ENT.Item> IsDif = service.IsDif(userIdentity, request.SolutionId, request.ItemId);

                    return new Data.GetItemSpecificVersionResponse(true, 0, string.Empty,
                        result.Data.ItemId,
                        result.Data.ItemName,
                        result.Data.ItemVersion,
                        result.Data.ItemParentId,
                        result.Data.ItemFolderId,
                        result.Data.ItemType,
                        new FileStream(absoluteFilePath, FileMode.Open, FileAccess.Read),
                       result.Data.ItemExtension);
                }
                Logger.DebugToTag(Library.LogTAG, string.Format("获取特定版本，项:{0},没有文件", result.Data.ItemName));
                return new Data.GetItemSpecificVersionResponse(true, 0, string.Empty,
                    result.Data.ItemId,
                        result.Data.ItemName,
                        result.Data.ItemVersion,
                        result.Data.ItemParentId,
                        result.Data.ItemFolderId,
                        result.Data.ItemType,
                    new MemoryStream(),
                    result.Data.ItemExtension);
            }
            Logger.DebugToTag(Library.LogTAG, string.Format("{0}获取特定版本，方案:{1},项:{2},失败", userIdentity, request.SolutionId, request.ItemId));
            return new Data.GetItemSpecificVersionResponse(false, 1, string.Empty,
                Guid.Empty,
                string.Empty,
                0,
                Guid.Empty,
                Guid.Empty,
                0,
                new MemoryStream(),
                string.Empty);
        }

        public ListResult<ItemStatus> GetItemChildrenStatus(GetLatestStatusRequest request)
        {
            List<ItemStatus> itemList = new List<ItemStatus>();
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.ItemService service = new Domain.Services.ItemService();

            SER.ListResult<ENT.Item> result = service.GetItemChildren(request.SolutionId, request.Id);
            if (result.IsSuccess)
            {
                foreach (var item in result.Data)
                {
                    Data.ItemStatus itemstatus = null;
                    if (!string.IsNullOrEmpty(item.Path))
                    {
                        itemstatus = new Data.ItemStatus();
                        itemstatus.ItemId = item.Id;
                        itemstatus.ItemName = item.Name;
                        itemstatus.ItemVersion = item.Version;
                        itemstatus.ItemParentId = item.ParentId;
                        itemstatus.ItemFolderId = item.FolderId;
                        itemstatus.ItemType = item.Type;
                        itemstatus.IsEditing = item.IsEditing;
                        itemstatus.Editor = item.Editor;
                        itemstatus.ExistInServer = true;
                        itemstatus.UpdateTime = item.Updatedtime;
                    }
                    else
                    {
                        itemstatus = new Data.ItemStatus();
                        itemstatus.ItemId = item.Id;
                        itemstatus.ItemName = item.Name;
                        itemstatus.ItemVersion = item.Version;
                        itemstatus.ItemParentId = item.ParentId;
                        itemstatus.ItemFolderId = item.FolderId;
                        itemstatus.ItemType = item.Type;
                        itemstatus.IsEditing = item.IsEditing;
                        itemstatus.Editor = item.Editor;
                        itemstatus.ExistInServer = false;
                        itemstatus.UpdateTime = item.Updatedtime;
                    }
                    itemList.Add(itemstatus);
                }
                Logger.DebugToTag(Library.LogTAG, string.Format("{0}获取最新状态，方案:{1},项:{2},成功,数量:{3}", userIdentity, request.SolutionId, request.Id, itemList.Count));
                return new ListResult<ItemStatus>(true, 0, string.Empty, itemList);
            }
            else
            {
                Logger.DebugToTag(Library.LogTAG, string.Format("{0}获取最新版本，方案:{1},项:{2},失败", userIdentity, request.SolutionId, request.Id));
                return new ListResult<ItemStatus>(false, 1, string.Empty, null);
            }
        }

        public Data.ServiceResult DeleteSolutionItem(DeleteSolutionItemRequest request)
        {
            string userIdentity = TokenUtil.GetUserIdentity(request.Token);
            SER.ItemService service = new Domain.Services.ItemService();

            SER.ServiceResult result = service.DeleteItem(userIdentity, request.SolutionId, request.ItemId);
            if (result.IsSuccess)
            {
                return new Data.ServiceResult(true, 0, string.Empty);
            }
            return new Data.ServiceResult(false, 1, string.Empty);
        }

        /// <summary>
        /// 获取特定方案下的所有项目列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ListResult<ItemHistory> GetSolutionItemListSV(GetSolutionItemListSVRequest request)
        {

            SER.ItemService service = new Domain.Services.ItemService();
            SER.ListResult<ENT.ItemHistory> result = service.GetSolutionItemListSV(request.SolutionId,request.Version);

            if (result.IsSuccess)
            {
                List<Data.ItemHistory> list = new List<Data.ItemHistory>();
                for (int index = 0; index < result.Data.Count; index++)
                {
                    Data.ItemHistory item = new Data.ItemHistory();
                    item.Id = result.Data[index].Id;
                    item.ItemId = result.Data[index].ItemId;
                    item.OperatedTime = result.Data[index].OperatedTime;
                    item.Operator = result.Data[index].Operator;
                    item.Version = result.Data[index].ItemVersion;
                   
                    list.Add(item);
                }

                return new Data.ListResult<Data.ItemHistory>(true, 0, string.Empty, list);
                //return list;
            }

            return new Data.ListResult<Data.ItemHistory>(false, 1, string.Empty, null);
        }

    }
}
